package com.whw.fy.utils;

import cn.hutool.crypto.asymmetric.RSA;
import com.whw.fy.entity.TokenInfo;
import com.whw.fy.entity.Staff;
import com.whw.fy.exception.InvalidTokenException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private Logger logger= LoggerFactory.getLogger(getClass());
    private static RSA rsa=new RSA(RSAUtils.getKeyFromFile("key.pri"), RSAUtils.getKeyFromFile("key.pub"));

     public static String createJwtToken(Staff staff)
    {

        Map claims= new HashMap<>();
        claims.put("staffId",staff.getStaffId());
        claims.put("staffJurisdiction",staff.getStaffJurisdiction());
        claims.put("staffName",staff.getStaffName());
        claims.put("staff_Job",staff.getStaffJob());
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(new Date().getTime()+2*60*60*1000))
                .setSubject(staff.getStaffId().toString())
                .signWith(rsa.getPrivateKey())
                .compact();
    }

    public static Claims resolveToken(String token)throws Exception {
        Jws<Claims> jws;
            jws = Jwts.parserBuilder()  // (1)
                    .setSigningKey(rsa.getPublicKey())         // (2)
                    .build()                    // (3)
                    .parseClaimsJws(token); // (4)
                    return jws.getBody();
            // we can safely trust the JWT
    }

    public static TokenInfo getTokenInfo(String token){
        try {
            Claims claims = resolveToken(token);
            TokenInfo tokenInfo=new TokenInfo();
                tokenInfo.setStaffId((Integer) claims.get("staffId"));
                tokenInfo.setStaffJurisdiction((Integer)claims.get("staffJurisdiction"));
                tokenInfo.setStaffName((String) claims.get("staffName"));
                tokenInfo.setStaffJob((String)claims.get("staff_job"));
            return tokenInfo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new InvalidTokenException();
        }

    }
}

